const {
	config
} = require('../../common/config.js')
const ServerError = require('../../common/error')

const db = uniCloud.database();

async function noticeAdd() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let addData = JSON.parse(httpInfo.body)
	let data = await db.collection("notice").add(addData)
	if (data.id) {
		return {
			errCode: 0,
			data: data,
			errMsg: "添加成功"
		}
	} else {
		throw new ServerError("添加失败", 3001)
	}
}
async function noticeDelete() {
	let httpInfo = this.getHttpInfo()
	let {
		_id
	} = JSON.parse(httpInfo.body)

	let {
		deleted
	} = await db.collection("notice").doc(_id).remove()
	if (deleted) {
		return {
			errCode: 0,
			data: {
				deleted
			},
			errMsg: "删除成功"
		}
	} else {
		throw new ServerError("没有可删除的数据", 3009)
	}

}
async function noticeUpdate() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let upData = JSON.parse(httpInfo.body)
	let _id = upData._id
	delete upData._id
	let {
		affectedDocs,
		updated
	} = await db.collection('notice').doc(_id).update(upData);
	if (updated > 0) {
		return {
			errCode: 0,
			data: {
				updated
			},
			errMsg: "更新"
		}
	} else {
		throw new ServerError("未知原因更新失败", 3012)
	}

}

async function noticeList(page = 0, limit = 10) {
	page = parseInt(page)
	limit = parseInt(limit)
	let {
		affectedDocs,
		data
	} = await db.collection('notice').get();
	return {
		errCode: 0,
		data: data,
		errMsg: "商品分类列表"
	}
}

module.exports = {
	noticeAdd,
	noticeDelete,
	noticeUpdate,
	noticeList,
}
